﻿using System;
using System.Data;
using System.Web.UI.WebControls;
using ASPNETVN.PORTAL.Components.Helpers;
using ASPNETVN.PORTAL.Components.Security;
using ASPNETVN.PORTAL.Components.UI;
using System.IO;

namespace ASPNETVN.PORTAL.Modules.FileExpress.Controls
{
    public partial class AddEditPackage : AddEditItemControl
    {
        private void buildCategory()
        {
            DataSet ds = Components.Category.SelectAll(this.ModuleID);
            DataRow[] rootRows = ds.Tables[0].Select("ParentID = 0");

            foreach (DataRow row in rootRows)
            {
                cbCategory.Items.Add(new ListItem(row["Name"].ToString(), row["ID"].ToString()));
                DataRow[] childRows = ds.Tables[0].Select("ParentID = " + row["ID"]);
                if (childRows.Length > 0)
                {
                    foreach (DataRow childRow in childRows)
                    {
                        cbCategory.Items.Add(new ListItem("» " + childRow["Name"], childRow["ID"].ToString()));
                    }
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            btnUpload.Enabled = btnDelete.Enabled = this.ItemID > 0;
            if (!IsPostBack)
            {
                this.buildCategory();

                if (this.ItemID > 0)
                {
                    Components.Package package = Components.Package.Load(this.ItemID);
                    if (package != null)
                    {
                        // Lĩnh vực.
                        cbCategory.SelectedValue = package.CategoryID.ToString();

                        // Tiêu đề.
                        txtTitle.Text = package.Title;

                        // Nội dung.
                        txtDescription.Text = package.Description;

                        // Hidden fields.
                        hfCreatedBy.Value = package.CreatedBy;
                        hfCreationTime.Value = package.CreationTime.ToString();
                    }
                }
            }
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                try
                {
                    int categoryID = cbCategory.SelectedValue == string.Empty ? 0 : Convert.ToInt32(cbCategory.SelectedValue);
                    if (cbCategory.SelectedItem.Text.IndexOf("»", 0, 1) < 0)
                    {
                        lblMsg.Text = "Chưa chọn đúng danh mục.";
                        return;
                    }

                    Components.Package package = new Components.Package();
                    package.CategoryID = categoryID;
                    package.Title = txtTitle.Text;
                    package.Description = txtDescription.Text;

                    int packageID = this.ItemID;

                    if (this.ItemID == 0)
                    {
                        package.CreatedBy = PortalSecurity.CurrentUser.Identity.Email;
                        package.CreationTime = DateTime.Now;
                        packageID = package.Insert();
                    }
                    else
                    {
                        package.CreatedBy = hfCreatedBy.Value;
                        package.CreationTime = Convert.ToDateTime(hfCreationTime.Value);
                        package.ID = Convert.ToInt32(this.ItemID);
                        package.Update();
                    }
                    // Refresh.
                    string url = string.Format("~/Default.aspx?tabindex={0}&tabid={1}&itemid={2}&mid={3}&page=AddEditPackage", this.TabIndex, this.TabID, packageID, this.ModuleID);
                    Response.Redirect(url);
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (this.ItemID > 0)
            {
                string uploadPath = this.Settings["UploadPath"].ToString();
                Components.Package.Delete(this.ItemID);
                DataSet ds = Components.Attachment.SelectBy_PackageID(this.ItemID);
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    string filename = Server.MapPath("~/" + uploadPath + "/FileExpress/" + this.ModuleID + "/" + row["FileName"]);
                    if (File.Exists(filename))
                    {
                        File.Delete(filename);
                    }
                }
                Response.Redirect(HttpUrlBuilder.BuildUrl(this.ModuleID, 0, ModulePages.Package));
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(HttpUrlBuilder.BuildUrl(this.ModuleID, 0, ModulePages.Package));
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            string url = string.Format("~/Default.aspx?tabindex={0}&tabid={1}&itemid={2}&mid={3}&page=FileUpload", this.TabIndex, this.TabID, this.ItemID, this.ModuleID);
            Response.Redirect(url);
        }
    }
}